# -*- encoding: utf-8 -*-
"""
Copyright 2011,2012 Ernesto Angel Celis de la Fuente 
		<celisdelafuente@gmail.com>

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless route_entity_keyuired by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""

import cgi
import datetime
import os
import urllib
import wsgiref.handlers

from google.appengine.ext import db
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.ext.webapp.util import run_wsgi_app

from models import Route
from models import RouteStop
from models import route_key

from bpauth import Default_settings

class MainPage(webapp.RequestHandler):
    def get(self):
        """
        user = users.get_current_user()
        if user:
            self.response.out.write('User: ' + user.nickname())
        else:
            self.redirect(user.create_login_url(selfroute_entity_keyuest.uri))
        """
        ''' TODO route_entity_key is the ancestor, not the entity key. Change this
        ASAP!!!
        '''
        route_ancestor = self.request.get('code') 

        if(route_ancestor == ''):
            routes = db.GqlQuery("SELECT * "
                                 "FROM Route "
                                 "ORDER BY color ASC")
            stops = ""
        else:
            routes = db.GqlQuery("SELECT * "
                                 "FROM Route "
                                 "WHERE ANCESTOR IS :1 "
                                 "ORDER BY color ASC",
                                 route_key(route_ancestor))

            stops = db.GqlQuery("SELECT * "
                                "FROM RouteStop "
                                "WHERE ANCESTOR IS :1 "
                                "ORDER BY lat_lon ASC",
                               route_key(route_ancestor))


        ''' TODO route_entity_key is the ancestor, not the entity key. Change this
        ASAP!!!
        '''
        template_values = {
            'code': route_ancestor,
            'routes': routes,
            'stops': stops,
            'colors':Default_settings.colors,
            'vehicles':Default_settings.vehicles
        }
        path = os.path.join(os.path.dirname(__file__), 
                             'bp-admin.html')
        self.response.out.write(template.render(path,
                                                template_values))


class RouteHandler(webapp.RequestHandler):
    def post(self):
        ''' TODO route_entity_key is the ancestor, not the entity key. 
        Change this ASAP!!!
        '''
        route_ancestor = self.request.get('code', 
                                                 default_value='01')

        route = Route(parent = route_key(route_ancestor),
                     code = route_ancestor,
                      color = self.request.get('color'),
                      description = self.request.get('description'),
                      vehicle = self.request.get('vehicle'),
                      geometry = self.request.get('geometry')
                     )
        route.put()
        self.redirect('/bp-admin/?' + urllib.urlencode(
            {'code': route_ancestor}))



class StopHandler(webapp.RequestHandler):
    def post(self):
        route_ancestor = self.request.get('code',
                                          default_value='01')

        stop = RouteStop(parent = route_key(route_ancestor),
                         description = self.request.get('description'),
                         geometry = self.request.get('geometry'),
                         route = route_key(route_ancestor)
                        )
        stop.put()
        self.redirect('/bp-admin/?' + urllib.urlencode(
            {'code':route_ancestor}))





# Everything starts here.
application = webapp.WSGIApplication([('/bp-admin/', MainPage),
                                      ('/bp-admin/route/addstop',StopHandler),
                                     ('/bp-admin/route/add', RouteHandler)],
                                     debug=True)

def main():
    run_wsgi_app(application)

if __name__ == "__main__":
    main()
